package datautils;

import org.apache.log4j.Logger;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import questionanswer.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Инесса
 * Date: 21.11.13
 * Time: 23:31
 * To change this template use File | Settings | File Templates.
 */
public class XMLQuestionSource {

    private static final Logger logger = Logger.getLogger(XMLQuestionSource.class);

    public List<Question> getQuestions(String path) {
        List<Question> questions = new LinkedList<>();

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(path);
            NodeList questionNodes = document.getElementsByTagName("question");
            for (int i = 0; i < questionNodes.getLength(); ++i) {
                Element questionElement = (Element) questionNodes.item(i);
                Node questionTextNode = questionElement.getElementsByTagName("questionText").item(0);
                Node themeNode = questionElement.getElementsByTagName("theme").item(0);
                Element answerElement = (Element) questionElement.getElementsByTagName("answer").item(0);
               // NodeList keyAnswers = answerElement.getElementsByTagName("keyAnswer");
                NodeList answerVariants = answerElement.getElementsByTagName("answerVariant");
                //начало моих костылей
                List<Node> keyAnswersList=null;
                for(int n=0;n<answerVariants.getLength();n++){
                   String correctAttribute = answerVariants.item(n).getAttributes().item(0).getNodeValue();
                   if (correctAttribute=="true")
                       keyAnswersList.add(keyAnswersList.size(),answerVariants.item(n));
                }
                NodeList keyAnswers=(NodeList)keyAnswersList;
                //конец
                questions.add(createQuestion(questionTextNode.getTextContent(),
                        themeNode.getTextContent(),
                        toStringArray(keyAnswers),
                        toStringArray(answerVariants)));
            }
        } catch (Throwable e) {
            logger.error("Can't process questions file.");
            // TODO think about rethrowing exception
        }
        return questions;
    }

    private Question createQuestion(String questionText, String theme, String[] keyAnswers, String[] answerVariants) {
        Answer answer;
        if (keyAnswers.length == 1 && answerVariants.length == 1) {
            answer = new OneAnswer(keyAnswers[0]);
        } else if (keyAnswers.length == 1 && answerVariants.length > 1) {
            answer = new OneAnswerFromMany(keyAnswers[0], answerVariants);
        } else {
            answer = new MultipleAnswer(keyAnswers, answerVariants);
        }
        return new Question(questionText, answer, theme);
    }

    private String[] toStringArray(NodeList list) {
        String[] strings = new String[list.getLength()];
        for (int i = 0; i < list.getLength(); ++i) {
            strings[i] = list.item(i).getTextContent();
        }
        return strings;
    }
}
